/*
    This file is part of the substandard lisp implementation of Standard Lisp
    Copyright (C) 2011 Nicky Nickell

    substandard lisp is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/*
    builtins related to function/macro declaration as defined in section
    3.5 of the The Standard Lisp Report
*/

function std_de(a, env) {
  var fname = a[0];
  var params = a[1];
  var fn = a[2];

  var func = new interpreted_function(fn, params, FTYPE_EXPR);

  env.functions.set(print(fname), func);

  return fname;
}
builtins['de'] = new builtin_function(std_de, 3, false, [TYPE_ID, TYPE_PAIR, CLASS_ANY], FTYPE_FEXPR);

function std_df(a, env) {
  var fname = a[0];
  var param = a[1];
  var fn = a[2];

  var func = new interpreted_function(fn, param, FTYPE_FEXPR);

  env.functions.set(print(fname), func);

  return fname;
}
builtins['df'] = new builtin_function(std_df, 3, false, [TYPE_ID, TYPE_PAIR, CLASS_ANY], FTYPE_FEXPR);

function std_dm(a, env) {
  var mname = a[0];
  var param = a[1];
  var fn = a[2];

  var func = new interpreted_function(fn, param, FTYPE_MACRO);

  env.functions.set(print(mname), func);

  return mname;
}
builtins['dm'] = new builtin_function(std_dm, 3, false, [TYPE_ID, TYPE_PAIR, CLASS_ANY], FTYPE_FEXPR);

function std_getd(a, env) {
  var fname = a[0];

  var func = env.functions.get(print(fname));

  if (func != UNDEFINED) {
    return new lisp_pair(new lisp_id(ftype_strings[func.ftype], env.oblist), func);
  } else {
    return NIL;
  }
}
builtins['getd'] = new builtin_function(std_getd, 1, false, [CLASS_ANY], FTYPE_EXPR);

function std_putd(a, env) {
  var fname = a[0];
  var type = a[1];
  var body = a[2];

  switch (type.value) {
  case 'expr':
    body.ftype = FTYPE_EXPR;
    break;
  case 'fexpr':
    body.ftype = FTYPE_FEXPR;
    break;
  case 'macro':
    body.macro = FTYPE_MACRO;
    break;
  default:
    // error?
  }

  env.functions.set(print(fname), body);

  return fname;
}
builtins['putd'] = new builtin_function(std_putd, 3, false, [TYPE_ID, CLASS_FTYPE, TYPE_FUNCTION], FTYPE_EXPR);

function std_remd(a, env) {
  var fname = a[0];

  throw new Error('REMD not implemented (yet)');
}
builtins['remd'] = new builtin_function(std_remd, 1, false, [TYPE_ID], FTYPE_EXPR);
